<template>
  <div class="store-child">
    <h4 class="font-medium text-gray-800 mb-3">状态管理 (Pinia Store) 演示：</h4>

    <div class="space-y-4">
      <!-- Store 状态显示 -->
      <div class="store-state">
        <h5 class="text-sm font-semibold text-gray-700 mb-2">全局状态</h5>
        <div class="space-y-2">
          <div class="state-item">
            <span class="state-label">计数值:</span>
            <span class="state-value">{{ count }}</span>
          </div>
          <div class="state-item">
            <span class="state-label">双倍值:</span>
            <span class="state-value">{{ doubleCount }}</span>
          </div>
          <div class="state-item">
            <span class="state-label">组件ID:</span>
            <span class="state-value">{{ componentId }}</span>
          </div>
        </div>
      </div>

      <!-- 持久化控制 -->
      <div class="persistence-control">
        <h5 class="text-sm font-semibold text-gray-700 mb-2">💾 持久化控制</h5>
        <div class="space-y-3">
          <!-- 持久化开关 -->
          <div class="flex items-center justify-between">
            <span class="text-sm">持久化存储:</span>
            <label class="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                :checked="isPersistenceEnabled"
                @change="handleTogglePersistence"
                class="sr-only peer"
              />
              <div
                class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"
              ></div>
            </label>
          </div>

          <!-- 存储信息 -->
          <div class="storage-info bg-gray-50 p-2 rounded text-xs">
            <div class="flex justify-between mb-1">
              <span>存储状态:</span>
              <span :class="isPersistenceEnabled ? 'text-green-600' : 'text-red-600'">
                {{ isPersistenceEnabled ? '✅ 已启用' : '❌ 已禁用' }}
              </span>
            </div>
            <div class="flex justify-between mb-1">
              <span>存储大小:</span>
              <span class="font-mono">{{ getStorageSize }} bytes</span>
            </div>
            <div class="flex justify-between">
              <span>最后更新:</span>
              <span class="font-mono">{{ formatDate(lastUpdated) }}</span>
            </div>
          </div>

          <!-- 持久化操作按钮 -->
          <div class="grid grid-cols-2 gap-2">
            <button
              @click="handleSaveToStorage"
              :disabled="!isPersistenceEnabled"
              class="px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              title="立即保存当前状态到本地存储"
            >
              💾 手动保存
            </button>
            <button
              @click="handleLoadFromStorage"
              class="px-3 py-2 bg-green-500 text-white rounded hover:bg-green-600 text-sm"
              title="从本地存储重新加载数据（如果存在）"
            >
              📂 重新加载
            </button>
            <button
              @click="handleClearStorage"
              class="px-3 py-2 bg-orange-500 text-white rounded hover:bg-orange-600 text-sm"
              title="删除本地存储的数据，但保留当前计数器状态"
            >
              🗑️ 清除存储
            </button>
            <button
              @click="handleFullReset"
              class="px-3 py-2 bg-red-500 text-white rounded hover:bg-red-600 text-sm"
              title="重置计数器为0，清除所有统计数据和本地存储（需确认）"
            >
              🔄 完全重置
            </button>
          </div>
        </div>
      </div>

      <!-- 组件本地状态 -->
      <div class="local-state">
        <h5 class="text-sm font-semibold text-gray-700 mb-2">本地状态与全局状态交互</h5>
        <div class="space-y-2">
          <div class="flex items-center space-x-2">
            <span class="text-sm">本地倍数:</span>
            <input
              v-model.number="localMultiplier"
              type="number"
              min="1"
              max="10"
              class="w-16 p-1 border rounded text-sm"
            />
            <span class="text-sm"
              >全局值 × {{ localMultiplier }} = {{ count * localMultiplier }}</span
            >
          </div>
          <button
            @click="syncToGlobal"
            class="px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm"
          >
            同步计算结果到全局
          </button>
        </div>
      </div>

      <!-- 操作历史 -->
      <div class="operation-history">
        <h5 class="text-sm font-semibold text-gray-700 mb-2">操作历史</h5>
        <div class="bg-gray-100 p-3 rounded max-h-32 overflow-y-auto">
          <div v-for="(history, index) in operationHistory" :key="index" class="text-xs mb-1">
            <span class="text-gray-500">{{ history.time }}</span>
            <span class="ml-2 text-blue-600">{{ history.action }}</span>
            <span class="ml-2 text-gray-600">{{ history.result }}</span>
          </div>
          <div v-if="operationHistory.length === 0" class="text-xs text-gray-500">暂无操作历史</div>
        </div>
      </div>
    </div>

    <!-- Store 说明 -->
    <div class="mt-4 p-3 bg-teal-50 border border-teal-200 rounded">
      <h5 class="text-sm font-medium text-teal-800 mb-2">🗃️ Pinia Store + 持久化说明</h5>
      <ul class="text-xs text-teal-700 space-y-1">
        <li>• <strong>全局状态管理</strong>：所有组件共享状态，数据一致性</li>
        <li>• <strong>响应式更新</strong>：状态变化自动同步，UI 自动更新</li>
        <li>• <strong>持久化存储</strong>：自动保存到 localStorage，刷新页面数据不丢失</li>
        <li>• <strong>版本控制</strong>：支持版本检查，避免数据格式冲突</li>
        <li>• <strong>灵活控制</strong>：可手动开关持久化，支持清除和重置</li>
      </ul>
    </div>

    <!-- 实现说明 -->
    <div class="mt-4 p-3 bg-indigo-50 border border-indigo-200 rounded">
      <h5 class="text-sm font-medium text-indigo-800 mb-2">⚙️ 技术实现</h5>
      <ul class="text-xs text-indigo-700 space-y-1">
        <li>• <strong>watch 监听</strong>：自动监听状态变化并保存到 localStorage</li>
        <li>• <strong>版本管理</strong>：避免不同版本数据结构冲突</li>
        <li>• <strong>错误处理</strong>：捕获存储异常，提供降级方案</li>
        <li>• <strong>性能优化</strong>：仅在数据变化时触发保存操作</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'

// 使用 store
const counterStore = useCounterStore()
const { count, doubleCount, isPersistenceEnabled, lastUpdated, getStorageSize } =
  storeToRefs(counterStore)

// 组件标识
const componentId = `StoreChild-${Math.random().toString(36).substr(2, 6)}`

// 本地状态
const localMultiplier = ref(2)

// 操作历史
interface OperationHistory {
  time: string
  action: string
  result: string
}

const operationHistory = ref<OperationHistory[]>([])

// 添加操作历史
const addHistory = (action: string, result: string) => {
  operationHistory.value.push({
    time: new Date().toLocaleTimeString(),
    action,
    result,
  })

  // 限制历史记录数量
  if (operationHistory.value.length > 8) {
    operationHistory.value.shift()
  }
}

const syncToGlobal = () => {
  const calculatedValue = count.value * localMultiplier.value
  const oldValue = count.value

  // 直接设置 store 的值
  counterStore.$patch({ count: calculatedValue })

  addHistory('同步计算结果', `${oldValue} × ${localMultiplier.value} = ${calculatedValue}`)
}

// 持久化相关方法
const handleTogglePersistence = () => {
  counterStore.togglePersistence()
  addHistory('切换持久化', `持久化状态: ${isPersistenceEnabled.value ? '关闭' : '开启'}`)
}

const handleSaveToStorage = () => {
  counterStore.saveToStorage()
  addHistory('手动保存', '数据已保存到本地存储')
}

const handleLoadFromStorage = () => {
  const success = counterStore.loadFromStorage()
  addHistory('重新加载', success ? '数据加载成功' : '无数据或加载失败')
}

const handleClearStorage = () => {
  counterStore.clearStorage()
  addHistory('清除存储', '本地存储数据已清除')
}

const handleFullReset = () => {
  // 添加确认对话框
  if (
    !confirm(
      '⚠️ 确定要完全重置吗？\n\n这将会：\n• 重置计数器为 0\n• 删除本地存储数据\n\n此操作不可撤销！',
    )
  ) {
    return
  }

  const oldValue = count.value

  counterStore.fullReset()

  addHistory('完全重置', `计数器: ${oldValue} → 0，存储已删除`)

  // 显示重置成功信息
  setTimeout(() => {
    addHistory('重置完成', '✅ 所有数据已重置，可以重新开始')
  }, 100)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未设置'
  try {
    return new Date(dateString).toLocaleString()
  } catch {
    return '无效日期'
  }
}

// 监听全局状态变化
watch(count, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    console.log(`[${componentId}] 检测到全局状态变化: ${oldValue} → ${newValue}`)
  }
})

// 组件初始化时添加记录
addHistory('组件初始化', `当前值: ${count.value}`)
</script>

<style scoped lang="scss">
.store-child {
  @apply border border-gray-200 rounded-lg p-4 bg-gray-50;
}

.store-state,
.local-state,
.operation-history,
.persistence-control {
  @apply p-3 bg-white rounded border border-gray-100;
}

.state-item {
  @apply flex justify-between items-center;
}

.state-label {
  @apply text-sm font-medium text-gray-600;
}

.state-value {
  @apply text-sm font-semibold text-gray-800 bg-gray-100 px-2 py-1 rounded;
}
</style>
